package com.config;

import com.utils.Commons;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;


@Component
public class MyInterceptre  implements HandlerInterceptor {
    private static final Set<String> exUrl = new HashSet<>();
    static {
        exUrl.add("/login");
        exUrl.add("/toLogin");
        exUrl.add("/logout");
        exUrl.add("/uploadFile");
        exUrl.add("/download");
        exUrl.add("/toUpload");
        exUrl.add("/toDownload");
        exUrl.add("/static/**");
        exUrl.add("/get/**");
        exUrl.add("/api/**");
        exUrl.add("/admin/login");
        exUrl.add("/admin/toLogin");
        exUrl.add("/ueUploadController/**");
    }
    @Autowired
    private Commons commons;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        String uri = request.getRequestURI();
        if (exUrl.contains(uri)){
            return true;
        }
        HttpSession session = request.getSession();
        if (uri.contains("/admin")){
            Object admin = session.getAttribute("admin");
            if (admin == null){
                response.sendRedirect("/admin/login");
                return false;
            }
            request.setAttribute("admin",admin);
        }else {
            Object user = session.getAttribute("user");
            if (user == null){
                response.sendRedirect("/login");
                return false;
            }
            request.setAttribute("user",user);
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, @Nullable ModelAndView modelAndView) throws Exception{
        request.setAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        request.setAttribute("commons",commons);
    }
    @Override
    public void afterCompletion(HttpServletRequest request,HttpServletResponse response,
                                Object handler, @Nullable Exception ex) throws Exception{

    }
}



